use std::fs;
use std::path::PathBuf;
use serde_json::{Value, json, to_string_pretty};
use dirs::home_dir;

#[derive(Debug, Clone)]
pub struct Config {
    pub input_methods: Vec<i32>,
    pub auto_start: bool,
}

impl Config {
    pub fn new() -> Self {
        Self {
            input_methods: vec![], // 默认空数组
            auto_start: false,
        }
    }

    pub fn load() -> Result<Self, Box<dyn std::error::Error>> {
        let config_path = Self::get_config_path();
        
        if !config_path.exists() {
            let config = Config::new();
            config.save()?;
            return Ok(config);
        }

        let content = fs::read_to_string(&config_path)?;
        let json: Value = serde_json::from_str(&content)?;
        
        let input_methods = if let Some(methods) = json["input_methods"].as_array() {
            methods
                .iter()
                .filter_map(|v| v.as_i64().map(|i| i as i32))
                .collect()
        } else {
            vec![2052, 1033]
        };

        let auto_start = json["auto_start"].as_bool().unwrap_or(false);

        Ok(Config {
            input_methods,
            auto_start,
        })
    }

    pub fn save(&self) -> Result<(), Box<dyn std::error::Error>> {
        let config_path = Self::get_config_path();
        
        // 确保配置目录存在
        if let Some(parent) = config_path.parent() {
            fs::create_dir_all(parent)?;
        }

        let json = json!({
            "input_methods": self.input_methods,
            "auto_start": self.auto_start
        });

        fs::write(&config_path, to_string_pretty(&json)?)?;
        Ok(())
    }

    pub fn get_config_path() -> PathBuf {
        let home = home_dir().unwrap_or_else(|| PathBuf::from("."));
        home.join(".utopia").join("config").join("im-select.json")
    }

    pub fn get_value(&self, key: &str) -> Option<String> {
        match key {
            "input_methods" => {
                if self.input_methods.is_empty() {
                    Some("[]".to_string())
                } else {
                    Some(self.input_methods.iter().map(|i| i.to_string()).collect::<Vec<_>>().join(" "))
                }
            },
            "auto_start" => Some(self.auto_start.to_string()),
            _ => None,
        }
    }

    pub fn set_value(&mut self, key: &str, value: &str) -> Result<(), Box<dyn std::error::Error>> {
        match key {
            "input_methods" => {
                let methods: Result<Vec<i32>, _> = value
                    .split_whitespace()
                    .map(|s| s.parse::<i32>())
                    .collect();
                self.input_methods = methods?;
            },
            "auto_start" => {
                self.auto_start = value.parse::<bool>()?;
            },
            _ => return Err(format!("未知配置项: {}", key).into()),
        }
        Ok(())
    }
} 